<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Image;

use think\Db;
use think\Exception;
use think\Request;

class Basicdata extends Base
{

    public function _initialize() {
        parent::_initialize();

        $this->searchFields = [
            'name' => [
                'label'     => '名称',
                'field'     => 'name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];
    }

    public function index() {
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere) {
                $where = array_merge($where, $this->defaultWhere);
            }
            $where['type'] = $param['type'];

            if ($param['type'] == 'crop') {
                $recursive = function ($parentId) use (&$recursive, $model, $where, &$data) {
                    $results = $model->where($where)->where(['parentId' => $parentId])->order('createDate DESC')->select();
                    foreach($results as $key => $value){
                        $data[] = $value;

                        $recursive($value['id']);
                    }
                };

                $recursive(0);
                $list = $data;
                //dump($list);die;
            } else {
                $list = $model->where($where)->order('createDate DESC')->limit($start, $length)->select();
            }

            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return parent::index();
    }

    public function add(Request $request)
    {
        return parent::add($request);
    }

    public function edit(Request $request)
    {
        return parent::edit($request);
    }

    public function savePost(Request $request, $redirect = ''){
        $redirect = url('admin/' . strtolower($this->model) . '/index', ['type' => $request->param('type')]);
        $model = model($this->model);
        if ($request->isPost()) {
            $data = $request->param();

            Db::startTrans();
            try {
                if ($data['name'] != $data['ori_name']) {
                    $exist = $model->where(['name' => $data['name'], 'type' => $data['type']])->field('name')->find();
                    if ($exist) {
                        Db::rollback();
                        return $this->error('该名称已经存在！');
                    }
                }

                if (isset($data['id']) && $data['id']) {
                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                    $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
                    $afterAction = '_after_update';
                } else {
                    $data['id'] = Helper::getUUID();
                    $result = $model->save($data);

                    $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
                    $afterAction = '_after_insert';
                }

                if($result !== false) {
                    // 单图
                    if(isset($data['imgId']) && !empty($data['imgId'])){
                        Image::where('id', $data['imgId'])->update(['relatedId' => $data['id'], 'relatedTable' => 'crop_data']);
                    }

                    // Query执行后的操作
                    $model->$afterAction($data);

                    // 写入日志
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('保存成功！', $redirect);
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
        } else {
            return $this->error('请求方式错误！');
        }
    }

    public function delete() {
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');
        $type = $request->param('type');
        if($id){
            Db::startTrans();
            try{
                if (isset($type) && $type == 'crop') {
                    $level1 = $model->where(['parentId' => $id, 'isDelete' => 2])->field('id')->find();
                    if ($level1) {
                        Db::rollback();
                        return $this->error('该分类有子分类，请先去删除子分类！');
                    }
                }

                $result = $model->where('id', $id)->update(['isDelete' => 1]);

                if($result !== false){
                    // Query执行后的操作
                    $model->_after_delete($id);

                    $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
                }else{
                    Db::rollback();
                    return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
                }
            }catch (Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());
            }
        }
    }

    /**
     * 检查类目名是否已存在
     */
    public function checkName(){
        if($this->request->isAjax()){
            $name = $this->request->param('name');
            $type = $this->request->param('type');
            $model = model($this->model);

            $result = $model->where(['name' => $name, 'type' => $type])->field('name')->find();

            if($result){
                return json(['status' => 1]);
            }else{
                return json(['status' => 0]);
            }
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);

            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        return $where;
    }
}
